package com.taoyibao.hongcanting.utils;

import android.text.TextUtils;

import com.taoyibao.hongcanting.constant.ApiConstant;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author TangAnna
 * @description:
 * @date :${DATA} 11:06
 */
public class DataUtils {

    /**
     * 网络请求时获取key
     *
     * @return
     */
    public static String getKey() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(date);
        String key = ApiConstant.KEY_STRAT + format;
        LogUtils.dNormal("MD5   ", "加密前=====" + key);
        String md5Key = md5(key);
        String md5UpperCase = md5Key.toUpperCase();
        LogUtils.dNormal("MD5   ", "加密后=====" + md5UpperCase);
        return md5UpperCase;
    }


    /**
     * 对String进行MD5加密
     *
     * @param string
     * @return
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分割集合数据 制定一组数据多少个分成几组
     *
     * @param list 总集合
     * @param len  每个集合要分几条数据
     * @return
     */
    public static List<List<?>> splitList(List<?> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }
        List<List<?>> result = new ArrayList<List<?>>();

        int size = list.size();
        int count = (size + len - 1) / len;

        for (int i = 0; i < count; i++) {
            List<?> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }
}
